#ifndef DATABASE_HPP
#define DATABASE_HPP

#include <QDebug>
#include <QDir>
#include <QTime>

enum
{
    EN_ID,
    EN_DATE,
    EN_TIME,
    EN_STATUS,
    EN_COMM,
    EN_MAX
};

typedef struct
{
    QString tab;
    int id;
    int date;
    int time;
    int status;
    QString comm;
} STU_DATA;

#define mQueryS(query, n) query.value(n).toString()
#define mQueryB(query, n) query.value(n).toByteArray()
#define mQueryStdS(query, n) query.value(n).toString().toStdString().data()
#define mQueryStdB(query, n) query.value(n).toByteArray().data()
#define mQueryI(query, n) query.value(n).toInt()


class CDatabase
{
private:
    QSqlDatabase m_db;

public:
    CDatabase()
    {
        // 建立文件存放目录
        QDir dir;
        dir.mkpath(".\\data");
    }
    ~CDatabase()
    {
        if (m_db.isOpen())
            m_db.close();
    }
    // 新建数据库
    bool create(const char *dbname = "./data/Single.db")
    {
        m_db = QSqlDatabase::addDatabase("QSQLITE");
        m_db.setDatabaseName(QString("%1").arg(dbname));

        if (!m_db.open())
        {
            qDebug() << "open database is error\n"
                     << m_db.lastError().text();
            QMessageBox::warning(0, QObject::tr("Database Error"),
                                 m_db.lastError().text());
            return false;
        }

        QSqlQuery query;
        bool bsuccess = query.exec("CREATE TABLE done ("
                                   "id INTEGER primary key autoincrement,"
                                   "date INTEGER,"
                                   "time INTEGER,"
                                   "status INTEGER,"
                                   "comm TEXT"
                                   ")");
        if (!bsuccess)
        {
            qDebug() << "create table is error: " << query.lastError().text();
        }

        bsuccess = query.exec("CREATE TABLE todo ("
                              "id INTEGER primary key autoincrement,"
                              "date INTEGER,"
                              "time INTEGER,"
                              "status INTEGER,"
                              "comm TEXT"
                              ")");
        if (!bsuccess)
        {
            qDebug() << "create table is error: " << query.lastError().text();
        }

        return true;
    }

    // 插入一条记录
    bool insert(STU_DATA *user)
    {
        QSqlQuery query;
        query.prepare(QString("insert into "
                              "%1(date,  time,  status,  comm) "
                              "values(:date, :time, :status, :comm)")
                          .arg(user->tab));

        query.bindValue(":date", user->date);
        query.bindValue(":time", user->time);
        query.bindValue(":status", user->status);
        query.bindValue(":comm", user->comm);
        if (!query.exec())
        {
            qDebug() << QString(QObject::tr("insert into failed: ")) + query.lastError().text();
            return false;
        }

        return true;
    }

    // 读取时间段内容
    void read(int start, int stop, QStringList &comm)
    {
        comm.clear();
        QSqlQuery query;
        query.exec(QString("SELECT * FROM done WHERE date>=%1 AND date<=%2")
                       .arg(start)
                       .arg(stop));
        while (query.next())
        {
            comm.append(query.value(EN_COMM).toString());
        }
    }

    // 根据ID删除记录
    bool deleteById(QString tabname, int id)
    {
        QSqlQuery query;
        bool bsuccess = query.exec(QString("DELETE FROM %1 WHERE id = %2").arg(tabname).arg(id));
        if (!bsuccess)
        {
            qDebug() << QString(QObject::tr("delete into failed: ")) + query.lastError().text();
            return false;
        }
        return true;
    }

    // 修改内容
    bool updateById(STU_DATA *data)
    {
        QSqlQuery query;
        query.prepare(QString("UPDATE %1 SET comm = :comm WHERE id=%2")
                          .arg(data->status == -1 ? "todo" : "done")
                          .arg(data->id));
        query.bindValue(":comm", data->comm);
        bool success = query.exec();
        if (!success)
        {
            qDebug() << QString(QObject::tr("update into failed: ")) + query.lastError().text();
            return false;
        }
        return true;
    }
};


class MyDateTime
{
public:
    int currentDateValue(qint64 adddays=0)
    {
        if(adddays==0)
        {
            return QDate::currentDate().toString("yyyyMMdd").toInt();
        }

        QDate date = QDate::currentDate();
        date = date.addDays(adddays);
        return date.toString("yyyyMMdd").toInt();
    }

    uint currentTimeValue()
    {
         return QDateTime::currentDateTime().toString("hhmmss").toUInt();
    }

    void weekStartStop(int *start,int *stop)
    {
        QDate date = QDate::currentDate();
        date = date.addDays(-date.dayOfWeek() + 1);
        *start = date.toString("yyyyMMdd").toInt();
        *stop = date.addDays(6).toString("yyyyMMdd").toInt();
    }

    int tostart(QString flg)
    {
        if (flg == "Today")
        {
            return currentDateValue();
        }
        else if (flg == "Week")
        {
            return currentDateValue(-QDate::currentDate().dayOfWeek()+1);
        }
        else if (flg == "7Day")
        {
            return currentDateValue(-7);
        }
        else if (flg == "Month")
        {
            return currentDateValue(-QDate::currentDate().day()+1);
        }
        else
        {
            return 20180326;
        }
    }
};


#endif // DATABASE_HPP
